package com.demo;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ShowMeBug {
    private double balance; // 账户余额
    ReentrantLock lock = new ReentrantLock();

    /**
     * 存款
     *
     * @param money 存入金额
     */
    public void deposit(double money) throws Exception {
        // todo
        boolean b = lock.tryLock(2, TimeUnit.SECONDS);
        if (!b) {
            return;
        }
        try {
            this.balance = this.balance + money;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获得账户余额
     */
    public double getBalance() {
        return balance;
    }

    public static void main(String[] args) throws InterruptedException {
        ShowMeBug account = new ShowMeBug();
        //todo:100线程并发
        long t1 = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {
                    account.deposit(1);
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(100));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
        countDownLatch.await();
        long t2 = System.currentTimeMillis();
        System.out.println("账户余额: " + account.getBalance() + ", time: " + (t2 - t1) + " ms");
    }
}